package io;

import java.io.*;

public class ClosingStreams {
    // 1. 传统方式：try-finally（Java 7之前）
    public static void traditionalClose() {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("file.txt");
            // 读取操作...
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 确保关闭流
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 2. try-with-resources（Java 7+，自动关闭）
    public static void tryWithResources() {
        // 资源在try括号中声明，会自动关闭（无需finally）
        try (FileInputStream fis = new FileInputStream("file.txt");
             FileOutputStream fos = new FileOutputStream("copy.txt")) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        // 流在这里自动关闭
    }

    // 3. 自定义资源释放（实现AutoCloseable接口）
    static class MyResource implements AutoCloseable {
        @Override
        public void close() throws Exception {
            System.out.println("自定义资源已关闭");
        }

        public void doSomething() {
            System.out.println("使用自定义资源");
        }
    }

    public static void customResource() {
        try (MyResource resource = new MyResource()) {
            resource.doSomething();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        traditionalClose();
        tryWithResources();
        customResource();
    }
}
